﻿using DoNet.Common.Cache;
using DoNet.Common.Const;
using DoNet.Common.Helpers;
using DoNet.Common.Result;
using DoNet.Common.VerificationCode;
using DoNet.Extensions.Common;
using DoNet.Extensions.Filters;
using DoNet.Extensions.Mvc;
using DoNet.System.Dtos;
using DoNet.System.IServices;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace DoNet.WebApi.Controllers
{
    /// <summary>
    /// 验证码接口
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class CaptchaController : BaseApiController
    {
        private readonly IServiceProvider serviceProvider;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="_logger"></param>
        public CaptchaController(ILogger<CaptchaController> _logger, ITokenService _tokenService, IServiceProvider _serviceProvider) : base(_logger, _tokenService)
        {
            serviceProvider = _serviceProvider;
        }

        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        [NoPermissionRequired]
        public CommonResult<AuthGetVerifyCodeOutputDto> CaptchaAsync()
        {
            var kvItem = CaptchaHelper.SimpleInput(4, false, true, false, false, false);
            var imgBase64 = kvItem.Key.Image_Base64.Substring(kvItem.Key.Image_Base64.IndexOf(',') + 1);

            CacheHelper cacheHelper = new CacheHelper(serviceProvider, true);
            TimeSpan expiresSliding = DateTime.Now.AddMinutes(5) - DateTime.Now;
            long vcodeId = IdGeneratorHelper.IdSnowflake();
            cacheHelper.Add(CacheConst.KeyVerCode + vcodeId.ToString(), kvItem.Value.DataCode, expiresSliding, false);
            AuthGetVerifyCodeOutputDto authGetVerifyCodeOutputDto = new AuthGetVerifyCodeOutputDto();
            authGetVerifyCodeOutputDto.Img = imgBase64;
            authGetVerifyCodeOutputDto.Key = vcodeId.ToString();
            CommonResult<AuthGetVerifyCodeOutputDto> commonResult = new CommonResult<AuthGetVerifyCodeOutputDto>();
            commonResult.ErrCode = ErrCode.successCode;
            commonResult.Success = true;
            commonResult.ResData = authGetVerifyCodeOutputDto;
            return commonResult;
        }
    }
}
